package StudyCode.summary.myfile;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.EnumSet;

import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class MoveSubTreeWithFileVisitor {
	public static void main(String[] args) throws IOException {
		Path moveFrom = Paths.get("E:/Move");
		Path moveTo = Paths.get("E:/Copy");

		MoveSubTree walk = new MoveSubTree(moveFrom, moveTo);
		EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

		Files.walkFileTree(moveFrom, opts, Integer.MAX_VALUE, walk);
	}
}

class MoveSubTree implements FileVisitor<Object> {
	private Path moveFrom, moveTo;
	private static FileTime time = null;

	MoveSubTree(Path moveFrom, Path moveTo) {
		this.moveFrom = moveFrom;
		this.moveTo = moveTo;
	}

	private static void moveSubTree(Path moveFrom, Path moveTo) {
		try {
			Files.copy(moveFrom, moveTo, REPLACE_EXISTING, COPY_ATTRIBUTES);
			Files.delete(moveFrom);
		} catch (IOException e) {
			System.err.println("不能移动 " + moveFrom + " [" + e + "]");
		}
	}

	@Override
	public FileVisitResult postVisitDirectory(Object dir, IOException exc) {
		Path newdir = moveTo.resolve(moveFrom.relativize((Path) dir));
		try {
			Files.setLastModifiedTime(newdir, time);
			Files.delete((Path) dir);
		} catch (IOException e) {
			System.err.println("不能删除: " + dir + " [" + e + "]");
		}

		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) {
		System.out.println("移动文件夹: " + dir);
		Path newdir = moveTo.resolve(moveFrom.relativize((Path) dir));
		try {
			Files.copy((Path) dir, newdir, REPLACE_EXISTING, COPY_ATTRIBUTES);
			time = Files.getLastModifiedTime((Path) dir);
		} catch (IOException e) {
			System.err.println("不能创建 " + newdir + " [" + e + "]");
			return FileVisitResult.SKIP_SUBTREE;
		}

		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) {
		System.out.println("移动文件: " + file);
		moveSubTree((Path) file, moveTo.resolve(moveFrom.relativize((Path) file)));
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFileFailed(Object file, IOException exc) {
		return FileVisitResult.CONTINUE;
	}
}
